<?php
App::uses('AppController', 'Controller');
/**
 * Stocks Controller
 *
 * @property Stock $Stock
 * @property PaginatorComponent $Paginator
 */
class StocksController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator','Custom');

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Stock->recursive = 1;
		$this->set('stocks', $this->Paginator->paginate());
               // $this->p($this->Paginator->paginate(),1);
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Stock->exists($id)) {
			throw new NotFoundException(__('Invalid stock'));
		}
		$options = array('conditions' => array('Stock.' . $this->Stock->primaryKey => $id));
		$this->set('stock', $this->Stock->find('first', $options));
		//$this->p($this->Stock->find('first', $options),1);
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Stock->create();
			if ($this->Stock->save($this->request->data)) {
				$this->Session->setFlash(__('The stock has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The stock could not be saved. Please, try again.'));
			}
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Stock->exists($id)) {
			throw new NotFoundException(__('Invalid stock'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->Stock->save($this->request->data)) {
				$this->Session->setFlash(__('The stock has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The stock could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Stock.' . $this->Stock->primaryKey => $id));
			$this->request->data = $this->Stock->find('first', $options);
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Stock->id = $id;
		if (!$this->Stock->exists()) {
			throw new NotFoundException(__('Invalid stock'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Stock->delete()) {
			$this->Session->setFlash(__('The stock has been deleted.'));
		} else {
			$this->Session->setFlash(__('The stock could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}

/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Stock->recursive = 0;
		$this->set('stocks', $this->Paginator->paginate());
	}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->Stock->exists($id)) {
			throw new NotFoundException(__('Invalid stock'));
		}
		$options = array('conditions' => array('Stock.' . $this->Stock->primaryKey => $id));
		$this->set('stock', $this->Stock->find('first', $options));
	}

/**
 * admin_add method
 *
 * @return void
 */
        function ranKey() {
            $this->autoRender = false;
        }
         function randomKey($length = 6) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
        }
         public function returnUploadPath() {
        return '/files/stock/';
        }
	public function admin_add() {
         
		$this->loadModel('Color');
		$this->loadModel('Category');
		$this->loadModel('Make');
		$this->loadModel('ModelDesc');
		$this->loadModel('Transmission');
		$this->loadModel('Country');
		$this->loadModel('Showroom');
		$this->loadModel('VehicleOption');
                $this->loadModel('StockImage');
		$this->loadModel('Stockoption');
                
		$this->set('VehicleOptionList',$this->VehicleOption->find('list'));
		$this->set('TransmissionList',$this->Transmission->find('list'));
		$this->set('colorList',$this->Color->find('list'));
		$this->set('CategoryList',$this->Category->find('list'));
		$this->set('MakeList',$this->Make->find('list'));
		$this->set('ModelDescList',$this->ModelDesc->find('list'));
		$this->set('CountryList',$this->Country->find('list'));
		$this->set('ShowroomList',$this->Showroom->find('list'));
		if ($this->request->is('post')) {
                   
                  
			$this->Stock->create();
			if ($this->Stock->save($this->request->data)) {
                            $StockID = $this->Stock->id;
                            $StockImagesArray = array();
                            ///vehicle options
                            $StockoptionsArray = array();
                                if(isset($this->request->data['Stock']['vo_abbrev']) && !empty($this->request->data['Stock']['vo_abbrev'])){
                                    foreach ($this->request->data['Stock']['vo_abbrev'] as $option) {
                                        $dataArray['vehicle_options_id'] = $option;
                                        $dataArray['stock_id'] =$StockID;
                                        $StockoptionsArray[] = $dataArray;
                                    }
                                    $this->Stockoption->saveAll($StockoptionsArray);
                                }
                        ///upload images
                        foreach ($this->request->data['Stock']['files'] as $Image) {
                        $this->StockImage->create();
                        $imageName = time() . '_' . $this->randomKey();
                        $ext = end(explode(".", $Image['name']));
                        $StockImagesArray['stock_id'] = $StockID;
                        $StockImagesArray['image_name'] = $imageName . '.' . $ext;
                      //  $StocjImagesArray['image_path'] = $StockID;
                        
                        
                        $originalImage = WWW_ROOT . $this->returnUploadPath() . 'original/' . $imageName . '.' . $ext;
                        $smallImage = WWW_ROOT . $this->returnUploadPath() . 'small/' . $imageName;
                        $largeImage = WWW_ROOT . $this->returnUploadPath() . 'large/' . $imageName;
                        $xsmallImage = WWW_ROOT . $this->returnUploadPath() . 'xsmall/' . $imageName;
                        if (move_uploaded_file($Image['tmp_name'], $originalImage)) {
                            $this->Custom->resize($originalImage, $smallImage, 268, 208);
                            $this->Custom->resize($originalImage, $largeImage, 545, 358);
                            $this->Custom->resize($originalImage, $xsmallImage, 108, 50);
                            $this->StockImage->save($StockImagesArray);
                           
                        } 
                        }
                           $this->Session->setFlash(__('The stock has been saved.'));
                           return $this->redirect(array('action' => 'index'));	
			} else {
				$this->Session->setFlash(__('The stock could not be saved. Please, try again.'));
			}
		}
	}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
                $this->loadModel('Color');
		$this->loadModel('Category');
		$this->loadModel('Make');
		$this->loadModel('ModelDesc');
		$this->loadModel('Transmission');
		$this->loadModel('Country');
		$this->loadModel('Showroom');
		$this->loadModel('VehicleOption');
                $this->loadModel('StockImage');
                $this->loadModel('Stockoption');
		
		$this->set('VehicleOptionList',$this->VehicleOption->find('list'));
		$this->set('TransmissionList',$this->Transmission->find('list'));
		$this->set('colorList',$this->Color->find('list'));
		$this->set('CategoryList',$this->Category->find('list'));
		$this->set('MakeList',$this->Make->find('list'));
		$this->set('ModelDescList',$this->ModelDesc->find('list'));
		$this->set('CountryList',$this->Country->find('list'));
		$this->set('ShowroomList',$this->Showroom->find('list'));
                $this->StockImage->recursive = -1;
                $this->set('StockImageArray',$this->StockImage->find('all',array('fields'=>'StockImage.id,StockImage.image_name','conditions'=>array('StockImage.stock_id'=>$id))));
		if (!$this->Stock->exists($id)) {
			throw new NotFoundException(__('Invalid stock'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->Stock->save($this->request->data)) {
                            ///image
                              $StockID = $id;
                            $StockImagesArray = array();
                            
                             ///vehicle options
                            $StockoptionsArray = array();
                                if(isset($this->request->data['Stock']['vo_abbrev']) && !empty($this->request->data['Stock']['vo_abbrev'])){
                                    $this->Stockoption->deleteAll(array('Stockoption.stock_id'=>$StockID));
                                    foreach ($this->request->data['Stock']['vo_abbrev'] as $option) {
                                        $dataArray['vehicle_options_id'] = $option;
                                        $dataArray['stock_id'] =$StockID;
                                        $StockoptionsArray[] = $dataArray;
                                    }
                                    $this->Stockoption->saveAll($StockoptionsArray);
                                }
                            
                            
                        ///upload images
                        foreach ($this->request->data['Stock']['files'] as $Image) {
                        $this->StockImage->create();
                        $imageName = time() . '_' . $this->randomKey();
                        $ext = end(explode(".", $Image['name']));
                        $StockImagesArray['stock_id'] = $StockID;
                        $StockImagesArray['image_name'] = $imageName . '.' . $ext;
                      //  $StocjImagesArray['image_path'] = $StockID;
                        
                        
                        $originalImage = WWW_ROOT . $this->returnUploadPath() . 'original/' . $imageName . '.' . $ext;
                        $smallImage = WWW_ROOT . $this->returnUploadPath() . 'small/' . $imageName;
                        $largeImage = WWW_ROOT . $this->returnUploadPath() . 'large/' . $imageName;
                        $xsmallImage = WWW_ROOT . $this->returnUploadPath() . 'xsmall/' . $imageName;
                        if (move_uploaded_file($Image['tmp_name'], $originalImage)) {
                            $this->Custom->resize($originalImage, $smallImage, 268, 208);
                            $this->Custom->resize($originalImage, $largeImage, 545, 358);
                            $this->Custom->resize($originalImage, $xsmallImage, 108, 50);
                            $this->StockImage->save($StockImagesArray);
                           
                        } 
                        }
                            
                            
                            ///image
                            
                          
				$this->Session->setFlash(__('The stock has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The stock could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Stock.' . $this->Stock->primaryKey => $id));
			$this->request->data = $this->Stock->find('first', $options);
		}
	}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_deleteimage($id = null,$sid = null) {
                $this->loadModel('StockImage');
		$this->StockImage->id = $id;
		if (!$this->StockImage->exists()) {
			throw new NotFoundException(__('Invalid Image'));
		}
		$this->request->onlyAllow('post', 'delete');
                $imagename = $this->StockImage->field('image_name');
		if ($this->StockImage->delete()) {
                        $fileoriginal = new File(WWW_ROOT . 'files/stock/original/'.$imagename, false, 0777);
                        $filelarge = new File(WWW_ROOT . 'files/stock/large/'.$imagename, false, 0777);
                        $filesmall = new File(WWW_ROOT . 'files/stock/small/'.$imagename, false, 0777);
                        $filexsmall = new File(WWW_ROOT . 'files/stock/xsmall/'.$imagename, false, 0777);
                       
                        $fileoriginal->delete(); 
                        $filelarge->delete();
                        $filesmall->delete();
                        $filexsmall->delete();
                        
			$this->Session->setFlash(__('The Image has been deleted.'));
		} else {
			$this->Session->setFlash(__('The Image could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'edit',$sid));
	}
	public function admin_delete($id = null) {
		$this->Stock->id = $id;
		if (!$this->Stock->exists()) {
			throw new NotFoundException(__('Invalid stock'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Stock->delete()) {
			$this->Session->setFlash(__('The stock has been deleted.'));
		} else {
			$this->Session->setFlash(__('The stock could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}}
